export function parseUrl(value: string) {
  const [url, search] = value.split("?");
  if (typeof search === "string") {
    const query = search?.split("&").reduce<Record<string, string>>((o, i) => {
      const [k, v] = i.split("=");
      o[k] = v;
      return o;
    }, {});
    return { url, query };
  } else {
    return { url, query: {} };
  }
}

export function queryStringify<T extends object>(query: T) {
  const search = Object.entries(query).reduce<string[]>((a, i) => {
    const [k, v = ""] = i;
    a.push(k + "=" + v);
    return a;
  }, []);
  return search.join("&");
}

export function appendDefaultQuery<T extends object>(value: string, params: T) {
  const parse = parseUrl(value);
  const query = queryStringify(Object.assign({}, params, parse.query));
  return parse.url + "?" + query;
}
